﻿using AutoMapper;
using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Traceability;
using MediatR;

namespace B.S.Database.Write.Api.Application.CommandHandler.Traceability
{
    public class TraceabilityUpdateCommandHandler : IRequestHandler<TraceabilityUpdateCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Basic_Traceability> traceabilityRepo;
        private readonly IMapper mapper;

        public TraceabilityUpdateCommandHandler(IBaseResotity<Basic_Traceability> TraceabilityRepo,IMapper mapper)
        {
            traceabilityRepo = TraceabilityRepo;
            this.mapper = mapper;
        }
        public Task<Apiresult<object>> Handle(TraceabilityUpdateCommands request, CancellationToken cancellationToken)
        {
            Apiresult<object> res = new Apiresult<object>();
            try
            {
                var entity = traceabilityRepo.GetAll().FirstOrDefault(c => c.TraceabilityId == request.TraceabilityId);
                if (entity == null)
                {
                    res.Code = ApiEnums.失败;
                    res.Message = "未找到要修改的数据";
                    return Task.FromResult(res);
                }
                // 更新字段
                entity.GoodsId = request.GoodsId;
                entity.Production_Batch = request.Production_Batch;
                entity.Quality_Guarantee = request.Quality_Guarantee;
                entity.Production_License = request.Production_License;
                entity.Manufacturing_Enterprise = request.Manufacturing_Enterprise;
                entity.Cover_Image = request.Cover_Image;
                entity.CreateTime = DateTime.Now;
                entity.UpdateName = request.UpdateName;
                // 如有其它字段可继续补充
                traceabilityRepo.Update(entity);
                res.Code = ApiEnums.成功;
                res.Message = "修改成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnums.失败;
                res.Message = ex.Message;
            }
            return Task.FromResult(res);
        }
    }
}
